package com.learning.demos;

import java.util.concurrent.TimeUnit;

/**
 * @author adolphw
 *
 * 死锁：是值两个或两个以上的进程在执行过程中，因争夺资源而造成的一种相互等待的现象，若无外力干涉那他们都将无法推进下去，如果系统资源充足，进程的请求
 * 都将能够得到满足，死锁的出现的可能性就很低，否则就会因为争夺有限的资源而陷入死锁。
 *
 */
public class DeadLockDemo {

    public static void main(String[] args) {
        String lockA = "locaA";
        String lockB = "lockB";

        new Thread(new HoldLockThread(lockA, lockB), "lockAaa").start();
        new Thread(new HoldLockThread(lockB, lockA), "lockBbb").start();

        /**
         * linux ps -ef ｜ grep xxx    ls -l
         *
         * windows 下的java运行程序 也有类似ps的查看进程的命令，但是我们目前只看java
         *  jps = java ps
         *  jps -l 定位进程号
         *  jstack 15682 找到死锁查看
         *
         *  Java stack information for the threads listed above:
         * ===================================================
         * "lockBbb":
         *         at com.learning.demos.HoldLockThread.run(DeadLockDemo.java:51)
         *         - waiting to lock <0x000000076ad13120> (a java.lang.String)
         *         - locked <0x000000076ad13158> (a java.lang.String)
         *         at java.lang.Thread.run(Thread.java:748)
         * "lockAaa":
         *         at com.learning.demos.HoldLockThread.run(DeadLockDemo.java:51)
         *         - waiting to lock <0x000000076ad13158> (a java.lang.String)
         *         - locked <0x000000076ad13120> (a java.lang.String)
         *         at java.lang.Thread.run(Thread.java:748)
         */

    }
}

class HoldLockThread implements  Runnable{
    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName() + "\t 自己持有" + lockA + "尝试获得" + lockB);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "\t 自己持有" + lockB + "尝试获得" + lockA);
            }
        }
    }
}